import 'dart:io';
import 'package:app/components/index.dart';
import 'package:app/util/AndroidChannel.dart';
import 'package:app/util/StringUtils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:path_provider/path_provider.dart';


class Upgrade extends StatefulWidget{

  final String? version;

  final String? serviceUrl;

  final String? context;

  final String? fileName;

  const Upgrade({super.key, this.version, this.serviceUrl, this.context, this.fileName});

  @override
  State<Upgrade> createState() => _UpgradeState(version, serviceUrl, context, fileName);

}

/// 我的
class _UpgradeState extends State<Upgrade>{

  final String? version;

  final String? serviceUrl;

  final String? text;

  final String? fileName;

  double _progress = 0;

  File? _file = null;

  final GlobalKey<NavigatorState> navigatorKey = GlobalKey();

  _UpgradeState(this.version, this.serviceUrl, this.text, this.fileName);

  /// 下载apk
  void downloadAndroid() async{
    Directory? storageDir = await getExternalStorageDirectory();
    String? storagePath = storageDir?.path;
    File file = File('${storagePath}/${fileName}');
    if(!file.existsSync()){
      file.createSync();
    }
    String url =  serviceUrl! + 'apk-prod/' + fileName!;
    var response = await Dio().get(url,
      onReceiveProgress: showDownloadProgress,
        options: Options(
          responseType: ResponseType.bytes,
          followRedirects: false
        )
    );
    file.writeAsBytesSync(response.data);
    setState(() => _file = file);
  }

  /// 显示下载进度
  void showDownloadProgress(int received, int total){
    var progress = (received / total * 100).toStringAsFixed(2);
    setState(() => _progress = double.parse(progress));
  }

  /// 开始安装
  void install(){
    String? apkFilePath = _file?.path;
    if(StringUtils.isNull(apkFilePath)){
      Error.of(context).show('安装失败，文件不存在');
      return;
    }
    InstallPlugin.installApk(apkFilePath!, appId: 'com.logistic.app').then((res){
      AndroidChannel.initChannels();
      AndroidChannel.restartApp();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor:const Color.fromARGB(255, 245, 245, 245),
      body: Column(
        children: [
          Container(
            height: MediaQuery.of(context).size.height,
            width: double.infinity,
            color: const Color.fromARGB(255, 255, 255, 255),
            child: Padding(
              padding: const EdgeInsets.only(left: 10, right: 10),
              child: Column(
                children: [
                  const Padding(
                    padding: EdgeInsets.only(top: 100),
                    child: Image(
                      image: AssetImage("assets/image/logo-2.png"),
                      width: 100,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 10, top: 20),
                    child: Text("V ${version}", style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w600),),
                  ),
                  const Padding(
                    padding: EdgeInsets.only(left: 10, top: 10),
                    child: Text("秦烟机物流平台", style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),),
                  ),
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Padding(
                      padding: const EdgeInsets.only(left: 20, top: 10, right: 20),
                      child: Text(text??'', style: const TextStyle(fontSize: 15),),
                    ),
                  ),
                  _progress != 0 && _progress != 100? Column(
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(left: 10, top: 50),
                        child: Text('${_progress.toString()}%', style: TextStyle(fontSize: 15, color: Colors.green, fontWeight: FontWeight.w600),),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 5, left: 20, right: 20),
                        child: LinearProgressIndicator(
                          value: _progress/100,
                          backgroundColor: Colors.grey,
                          valueColor: const AlwaysStoppedAnimation<Color>(Colors.green),
                        ),
                      ),
                    ],
                  ) : _progress == 100 ?
                  const Padding(
                    padding: EdgeInsets.only(top: 50),
                    child: Text('下载完成', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Colors.green),),
                  ) : Container(),
                  SizedBox(
                    width: MediaQuery.of(context).size.width,
                    child: Padding(
                      padding: const EdgeInsets.only(top: 50, left: 20, right: 20),
                      child: _progress == 0 ? Button(
                        onPressed: downloadAndroid,
                        label: '立即更新',
                        height: 60,
                        fontSize: 18,
                        circular: 50,
                      ) :
                      _progress == 100 ? Button(
                        onPressed: install,
                        label: '安装',
                        height: 60,
                        fontSize: 18,
                        circular: 50,
                      ) : Container(),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}